package com.example.gymnasiumsystem.servlet;

import com.example.gymnasiumsystem.dao.GymInfoDAO;
import com.example.gymnasiumsystem.enity.GymInfo;
import com.example.gymnasiumsystem.enity.PageRequest;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/GymList")
public class GymList extends HttpServlet {
    GymInfoDAO gymInfoDAO=new GymInfoDAO();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");  // 设置请求字符编码为UTF-8
        response.setContentType("text/html;charset=UTF-8");  // 设置响应字符编码为UTF-8
        // 获取所有活动信息
        String pageNumStr = request.getParameter("pageNum");
        int pageNum=1;
        if(pageNumStr!=null){
            pageNum=Integer.parseInt(pageNumStr);
        }
        List<GymInfo> gymInfos = gymInfoDAO.getGymsByPage(pageNum,5);
        List<GymInfo>gymInfos1=gymInfoDAO.getAllGyms();
        int t=gymInfos1.size();
        // 判断请求类型，如果是 AJAX 请求（期待 JSON 数据），返回 JSON 数据
        String acceptHeader = request.getHeader("Accept");
        if (acceptHeader != null && acceptHeader.contains("application/json")) {
            // 设置响应内容类型为 JSON
            response.setContentType("application/json;charset=UTF-8");

            // 将活动数据转换为 JSON 格式并写入响应
            Gson gson = new Gson();
            String json = gson.toJson(new GymResponse(gymInfos,t,pageNum));
            response.getWriter().write(json);
        } else {
            // 否则，返回 HTML 页面（转发给 JSP）
            response.sendRedirect("admin/gymList.jsp");
        }
    }

    // 用于封装返回的数据格式
    private static class GymResponse {
        private List<GymInfo> gymInfos;
        int totalCount=0;
        PageRequest pageRequest;

        public GymResponse(List<GymInfo> gymInfos,int t,int pageNum) {
            this.gymInfos = gymInfos;
            this.totalCount=t;
            this.pageRequest=new PageRequest();
            this.pageRequest.setPageNum(pageNum);
        }

        public List<GymInfo> getActivities() {
            return gymInfos;
        }
    }
}
